/****************************************************************************
  From Qt Examples
****************************************************************************/

#include <QtGui>
#include <QtNetwork>

#include <stdlib.h>

#include "dialog.h"
#include "server.h"
#include "ui_dialog.h"


Dialog::Dialog(QWidget *parent)
    : QDialog(parent),
      ui(new Ui::Dialog)
{
    ui->setupUi(this);

    //proxyHostLabel = new QLabel(tr("&Proxy address:"));
    //proxyPortLabel = new QLabel(tr("&Proxy port:"));


    //statusLabel = new QLabel;
   // sendServerDataButton = new QPushButton(tr("SendData")); // connect the signal-slot to the timer signal
    //quitButton = new QPushButton(tr("Quit"));
    ui->quitButton->setAutoDefault(false);
    //ui->connectToProxyButton = new QPushButton(tr("ConnectToProxy"));

    //quint16 portNumber = 5001;

    QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
    // use the first non-localhost IPv4 address
    for (int i = 0; i < ipAddressesList.size(); ++i) {
        if (ipAddressesList.at(i) != QHostAddress::LocalHost &&
            ipAddressesList.at(i).toIPv4Address()) {
            ipAddress = ipAddressesList.at(i).toString();
            break;
        }
    }

    // if we did not find one, use IPv4 localhost
    if (ipAddress.isEmpty())
        ipAddress = QHostAddress(QHostAddress::LocalHost).toString();

    if (!server.listen(QHostAddress(ipAddress), server.serverPort())) {     //(!server.listen(QHostAddress::Any,portNumber)) {
        QMessageBox::critical(this, tr("Threaded Server"),
                              tr("Unable to start the server: %1.")
                              .arg(server.errorString()));
        close();
        return;
    }

    ui->statusLabel->setText(tr("The server is running on\n\nIP: %1\nport: %2\n\n"
                            "Run the Client.")
                         .arg(ipAddress).arg(server.serverPort()));

    //Add the line and text edit
    //serverTextEdit = new QTextEdit();
    //serverLineEdit = new QLineEdit();


    ui->proxyHostLineEdit->setText(ipAddress);
    ui->proxyPortLineEdit->setText("5001");
    ui->proxyPortLineEdit->setValidator(new QIntValidator(1, 65535, this));

    //ui->proxyHostLabel->setBuddy(proxyHostLineEdit);
    //ui->proxyPortLabel->setBuddy(proxyPortLineEdit);

    //SIGNALS/SLOTS
    connect(ui->quitButton, SIGNAL(clicked()), this, SLOT(close()));
    //connect(serverLineEdit,SIGNAL(returnPressed()),this,SLOT(send()));
    connect((&server),SIGNAL(transferMessage(QString)),this,SLOT(readCMsg(QString)));
    // Set Hardware Spec
    connect(this,SIGNAL(sendHardwareSpec(double, double, unsigned int, unsigned int)),
            (&server),SLOT(setHardwareSpec(double, double, unsigned int, unsigned int)));

    // Proxy related connections
    connect(ui->connectToProxyButton, SIGNAL(clicked()),this,SLOT(connectToProxy()));
    connect(ui->sendServerDataButton, SIGNAL(clicked()), this, SLOT(sendServerDataToProxy()));

    ui->MTTFLineEdit->setText("1");
    ui->MTTRLineEdit->setText("1");
    ui->clockSpeedLineEdit->setText("1");
    ui->IPCLineEdit->setText("1");

    unsigned int mttfInSecond = (unsigned int)(31556926 * (double) ui->MTTFLineEdit->text().toDouble());
    unsigned int mttrInSecond = (unsigned int)(3600 * (double) ui->MTTRLineEdit->text().toDouble());

    emit sendHardwareSpec(ui->clockSpeedLineEdit->text().toDouble(),
                          ui->IPCLineEdit->text().toDouble(),
                          mttfInSecond, mttrInSecond);

    /*
    QHBoxLayout *buttonLayout = new QHBoxLayout;
    buttonLayout->addStretch(1);
    buttonLayout->addWidget(quitButton);
    buttonLayout->addStretch(1);
    buttonLayout->addWidget(sendServerDataButton);
    buttonLayout->addStretch(1);
    buttonLayout->addWidget(connectToProxyButton);

    QVBoxLayout *mainLayout = new QVBoxLayout;
    //mainLayout->addWidget(serverTextEdit);
    //mainLayout->addWidget(serverLineEdit);
    mainLayout->addWidget(statusLabel);
    mainLayout->addLayout(buttonLayout);
    mainLayout->addWidget(proxyHostLabel);//,2,0);
    mainLayout->addWidget(proxyHostLineEdit);//,2,1);
    mainLayout->addWidget(proxyPortLabel);//,3,0);
    mainLayout->addWidget(proxyPortLineEdit);//,3,1);
    setLayout(mainLayout);*/

    setWindowTitle(tr("Server"));

    //tessting
    //connectionD = new QTcpSocket();
}

void Dialog::readCMsg(QString msg)
{
    qDebug() << "MSG Recived!!: " << msg;
    //serverTextEdit->append(msg);

}


void Dialog::connectToProxy()
{
    qDebug() << "Sending proxy info to the server"
                + ui->proxyHostLineEdit->text() + ui->proxyPortLineEdit->text();

    server.ProxyConnection(ui->proxyHostLineEdit->text(), ui->proxyPortLineEdit->text().toInt());
    ui->connectToProxyButton->setEnabled(false);
}


void Dialog::sendServerDataToProxy()
{
    qDebug() << "Forwarding server info to the proxy" ;

    // Server port is quint16
    // Append more server related calculations here (amount of connections etc...)
    // May have that info available in the model(the Server.cpp) instead of the view (dialog.cpp)
    serverData = ipAddress + "::" + QString::number(server.serverPort(),10);
    qDebug() << "From dialog: " << serverData;
    server.sendServerData(serverData);
}

void Dialog::on_setButton_clicked()
{
    unsigned int mttfInSecond = (unsigned int)(31556926 * (double) ui->MTTFLineEdit->text().toDouble());
    unsigned int mttrInSecond = (unsigned int)(3600 * (double) ui->MTTRLineEdit->text().toDouble());

    emit sendHardwareSpec(ui->clockSpeedLineEdit->text().toDouble(),
                          ui->IPCLineEdit->text().toDouble(),
                          mttfInSecond, mttrInSecond);
}

void Dialog::serverStarted()
{
    ui->clockSpeedLineEdit->setEnabled(false);
    ui->IPCLineEdit->setEnabled(false);
    ui->MTTFLineEdit->setEnabled(false);
    ui->MTTRLineEdit->setEnabled(false);
    ui->setButton->setEnabled(false);
}
